package com.service.scheduling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.dao.constants.ConfigConstants;
import com.service.dao.enums.CommonStatusEnums;
import com.service.dao.mapper.SysConfigMapper;
import com.service.dao.model.SysConfig;
import com.service.scheduling.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <dl>
 * <dt>platform</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2018</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019-04-06</dd>
 * </dl>
 */
@Slf4j
@Service
public class ConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ConfigService {

    @Override
    public SysConfig getByConfigName(String configName) {
        return getOne(new QueryWrapper<SysConfig>().lambda().eq(SysConfig::getConfName, configName)
                .eq(SysConfig::getConfStatus, CommonStatusEnums.ACTIVE.getCode()));
    }

    @Override
    public List<SysConfig> listByConfigGroup(Integer configGroup) {
        return list(new QueryWrapper<SysConfig>().lambda()
                .eq(SysConfig::getConfGroup, configGroup)
                .eq(SysConfig::getConfStatus, CommonStatusEnums.ACTIVE.getCode()));
    }

    @Override
    public Map<String, SysConfig> mapByConfigGroup(Integer configGroup) {
        List<SysConfig> sysConfigs = listByConfigGroup(configGroup);
        return sysConfigs.parallelStream().collect(Collectors.toMap(SysConfig::getConfName, a -> a));
    }

    @Override
    public Map<String, SysConfig> mapByConfigGroup(List<Integer> groupList) {
        return list(new QueryWrapper<SysConfig>().lambda()
                .in(SysConfig::getConfGroup, groupList)
                .eq(SysConfig::getConfStatus, CommonStatusEnums.ACTIVE.getCode())).parallelStream()
                .collect(Collectors.toMap(SysConfig::getConfName, a -> a));
    }

    @Override
    public Date getOrderOverdueTime() {
        SysConfig config = this.getByConfigName(ConfigConstants.ORDER_OVERDUE_TIME);
        if (ObjectUtils.isEmpty(config) || Integer.parseInt(config.getConfValue()) <= 0) {
            return null;
        }

        return DateUtils.addMinutes(new Date(), Integer.parseInt(config.getConfValue()) * -1);
    }
}
